<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/8
 * Time: 11:25
 */

/**
 * @param $topicId
 * @return array|null
 */
include_once __DIR__ . DIRECTORY_SEPARATOR . '../http/ResponseResult.php';
include_once __DIR__ . DIRECTORY_SEPARATOR . 'TopicService.php';
include_once __DIR__ . DIRECTORY_SEPARATOR . 'SessionService.php';

/**
 * @param $topicId
 * @return array|null
 */
function getReplyByTopicId($topicId)
{
    $db = require "DatabaseService.php";
    $result = mysqli_query($db, "SELECT t.*, u.access, ud.avatar from users u, users_data ud, topics_reply t where u.id = t.users_id and t.topics_id = '{$topicId}' and u.id = ud.users_id AND t.is_deleted = FALSE;");
    if (!$result) {
        return [];
    }
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

/**
 * @return mixed
 */
function createReplyByPost() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        responseError(1000, 'Not Find 404');
    }

    if (!checkLogin()) {
        responseError(2000, 'Not Login');
    }
    $data = $_POST;
    $topicId = (int)(isset($data['topic_id']) ? $data['topic_id'] : 0);
    $content = isset($data['content']) ? $data['content'] : null;

    if ($topicId == 0 || $content == null) {
        responseError(3000, '参数不正确');
    }
    $topic = findTopicById($topicId);
    if (empty($topic)) {
        responseError(4000, '帖子不存在');
    }
    $user = getUser();
    $replyId = createReply($user['users_id'], $topicId, $content);
    return $replyId;
}

/**
 * @param $uid
 * @param $topicId
 * @param $content
 * @return mixed
 */
function createReply($uid, $topicId, $content) {
    $db = require 'DatabaseService.php';
    $stmt = mysqli_prepare($db, "INSERT INTO topics_reply ( users_id, topics_id, content) VALUES (?, ?, ?)");
    $content = mysqli_real_escape_string($db, $content);
    mysqli_stmt_bind_param($stmt, 'iis', $uid, $topicId, $content);
    mysqli_stmt_execute($stmt);
    return mysqli_stmt_insert_id($stmt);
}

/**
 * @param $reply_id
 * @return array|null
 */
function getTopicReplyById($reply_id) {
    $db = require 'DatabaseService.php';
    $result =mysqli_query($db, "select * from topics_reply WHERE id = '{$reply_id}' AND is_deleted = FALSE LIMIT 1");
    return mysqli_fetch_assoc($result);
}

function deleteReply($reply_id) {
    $db = require 'DatabaseService.php';
    $result =mysqli_query($db, "UPDATE topics_reply SET is_deleted = TRUE WHERE id = '{$reply_id}' LIMIT 1");
    return mysqli_num_rows($result);
}